
using UnityEngine;
using System.Collections;
 
public class PveCameraScreenEffect : MonoBehaviour {
 
    [SerializeField][Range (0, 1)]
    public float darkPercent;
    public Color color;
    public Shader shader;
    private Material curMaterial;

    private int state;
    private float fadeTime;
    private float fadeStartTime;
    
    public Material material
    {
        get
        {
            if (curMaterial == null)
            {
                curMaterial = new Material(shader);
                curMaterial.hideFlags = HideFlags.HideAndDontSave;
            }
            return curMaterial;
        }
    }
 
    void Start()
    {
        if (SystemInfo.supportsImageEffects == false)
        {
            enabled = false;
            return;
        }
 
        if (shader != null && shader.isSupported == false)
        {
            enabled = false;
        }
    }
 
    void OnDisable()
    {
        if (curMaterial)
        {
            DestroyImmediate(curMaterial);
        }
    }
 
    void Update()
    {
        if (state != 0)
        {
            var percent = (Time.time - fadeStartTime) / fadeTime;
            if (state == 1)
            {
                darkPercent = percent;
            }
            else
            {
                darkPercent = 1 - percent;
            }

            if (percent >= 1)
            {
                state = 0;
            }
        }
        color = Color.Lerp(Color.white, Color.black, darkPercent);
    }
 
    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (shader != null)
        {
            material.SetColor("_Color", color);
            Graphics.Blit(source, destination, material);
        }
        else
        {
            Graphics.Blit(source, destination);
        }
    }

    public void BlackIn(float time)
    {
        state = 1;
        fadeStartTime = Time.time;
        fadeTime = time;
    }

    public void BlackOut(float time)
    {
        state = 2;
        fadeStartTime = Time.time;
        fadeTime = time;
    }
}